package com.wan37.logic.chat.handler;

import com.wan37.logic.chat.cache.ChatCache;
import com.wan37.logic.chat.service.PrivateChatService;
import com.wan37.logic.chat.util.ChatRouteUtil;
import com.wan37.logic.chat.domain.vo.ChatVO;
import com.wan37.logic.component.Worker;
import com.wan37.logic.db.AsynDBManager;
import com.wan37.logic.domain.vo.MessageVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.MsgHandler;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.client2server.game.GameChat;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 私聊处理消息
 *
 * @author : luoyong
 * @date : 2020-07-15 09:51
 **/
public class CGameOneToOneChatHandler extends MsgHandler {
    private ChatCache chatCache;
    private ChatRouteUtil chatRouteUtil;
    private AsynDBManager asynDBManager;
    private PrivateChatService privateChatService;
    /**
     * MsgHandler构造函数
     *
     * @param messageVO
     */
    public CGameOneToOneChatHandler(MessageVO messageVO) {
        super(messageVO);
        this.chatCache = SpringContextHolder.getBean("chatCache");
        this.chatRouteUtil = SpringContextHolder.getBean("chatRouteUtil");
        this.asynDBManager = SpringContextHolder.getBean("asynDBManager");
        this.privateChatService = SpringContextHolder.getBean("privateChatService");
    }

    @Override
    public void execute(Worker worker) throws Exception {
        GameChat.OneToOneChat oneToOneChat = (GameChat.OneToOneChat) messageVO.getMessage();
        /**
         * 将私聊消息缓存起来
         */
//        if (!chatCache.getUserIdToChatIn().get(messageVO.getUserId())
//                .getOneChatVOListMap().containsKey(oneToOneChat.getReceiverId())) {
//            chatCache.getUserIdToChatIn().get(messageVO.getUserId())
//                    .getOneChatVOListMap().put(oneToOneChat.getReceiverId(), new CopyOnWriteArrayList<>());
//        }
        ChatVO chatVO = new ChatVO(oneToOneChat.getSenderId(), oneToOneChat.getContent());
        chatCache.getUserIdToChatIn().get(messageVO.getUserId()).getOneChatVOListMap()
                .get(oneToOneChat.getReceiverId()).add(chatVO);
        asynDBManager.distributeWork(messageVO.getUserId(), ()->privateChatService.save(chatVO, oneToOneChat.getReceiverId()));
        chatRouteUtil.sendChatResponse(PtoNum.ONETOONECHAT, oneToOneChat.getReceiverId(), chatVO);
    }
}
